package com.code.telegram.managers;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.code.models.robot.FocusOnTwitterFailure;
import com.code.telegram.results.ClientResponse;
import com.code.telegram.services.ChatTwitterService;
import com.google.common.collect.Maps;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.User;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * http调用的相关管理类
 *
 * @author xiaoyaowang
 */
@Component
public class HttpManager {

    private static Logger log = LoggerFactory.getLogger(HttpManager.class);

    private static final String TWITTER_URL = "https://api.twitter.com/1.1";

    private static final String ACCEPT = "Accept";

    private static final String CLIENT_TYPE = "clienttype";

    private static final String HAND_SHAKE = "handshake";

    private static final String IMIE = "imie";

    private static final String RANDOM = "random";

    private static final String TRAN_CODE = "trancode";

    private static final String LANGUAGE = "language";

    private static final String SOURCE = "source";

    private static final String VERSION = "version";

    private static final String WALLET_ID = "walletid";

    private static final String HEADER = "header";

    private static final String BODY = "body";

    private static final String COIN_ADDR = "coinAddr";

    @Value("${wallet.url}")
    private String walletUrl;

    @Value("${token.swap.url}")
    private String url;

    @Value("${telegram.url}")
    private String telegramUrl;

    @Value("${twitter.bearerToken}")
    private String bearerToken;

    @Value("${twitter.account}")
    private String twitterAccount;

    @Value("${listen.join.group.token}")
    private String collectToken;

    @Value("${check.image-url}")
    private String checkImageUrl;

    @Value("${task.token}")
    private String taskToken;

    @Autowired
    private RestTemplate restTemplate;

    @Resource
    private ChatTwitterService chatTwitterService;

    /**
     * 校验相关币种地址
     *
     * @param coinAddress 币种地址
     * @return 币种地址验证结果
     */
    public Boolean verifyCoinAddress(String coinAddress) {
        if (StringUtils.isBlank(coinAddress)) {
            return false;
        }
        //设置请求参数
        Map<String, Object> postData = Maps.newHashMapWithExpectedSize(1 << 4);
        //请求头部分
        Map<String, Object> header = Maps.newHashMapWithExpectedSize(1 << 4);
        header.put(CLIENT_TYPE, "Android");
        header.put(HAND_SHAKE, "5d952d455fbcde485f621347da2760f7");
        header.put(IMIE, "d6013be3b8c4db433f40152778080901");
        header.put(LANGUAGE, "zh");
        header.put(RANDOM, "1621445148105");
        header.put(SOURCE, "xbit");
        header.put(TRAN_CODE, "wallet_coinAddrIsExist");
        header.put(VERSION, "1.0.9");
        header.put(WALLET_ID, "9169590a501fd987fd8c5920631c37283313085a");
        postData.put(HEADER, header);
        //请求体部分
        Map<String, Object> reqBody = Maps.newHashMapWithExpectedSize(1 << 4);
        reqBody.put(COIN_ADDR, coinAddress);
        postData.put(BODY, reqBody);
        String requestBody = JSON.toJSONString(postData);
        log.info("请求体数据：【{}】", requestBody);
        HttpEntity<String> formEntity = new HttpEntity<>(requestBody, getJsonHeader());
        HttpMethod method = HttpMethod.POST;
        ResponseEntity<ClientResponse> response = restTemplate.exchange(url + "/lightwallet/server/process", method, formEntity, ClientResponse.class);
        log.info("校验钱包地址的响应结果:{}", JSON.toJSONString(response));
        ClientResponse body = response.getBody();
        int rtnCode = body.getRtnCode();
        if (rtnCode == 1) {
            JSONObject dataJsonObject = JSON.parseObject(JSON.toJSONString(body.getData()));
            if (null != dataJsonObject && dataJsonObject.containsKey("exist")) {
                Boolean verifyResult = (Boolean) dataJsonObject.get("exist");
                log.info("地址验证结果：【{}】", verifyResult);
                return verifyResult;
            }
        } else {
            return false;
        }
        return false;
    }

    /**
     * 根据文件id获取文件的路径
     *
     * @param token  机器人的token
     * @param fileId 文件的id
     * @return 文件路径
     */
    public String getFilePath(String token, String fileId) {
        String uri = telegramUrl + "/bot" + token + "/getfile?file_id=" + fileId;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> entity = new HttpEntity<>(headers);
        String strBody = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class).getBody();
        JSONObject resultJson = JSON.parseObject(strBody);
        if (null != resultJson && resultJson.containsKey("ok")) {
            boolean ok = resultJson.getBoolean("ok");
            if (ok) {
                if (resultJson.containsKey("result")) {
                    JSONObject result = resultJson.getJSONObject("result");
                    if (null != result) {
                        String filePath = result.getString("file_path");
                        filePath = telegramUrl + "/file/bot" + token + "/" + filePath;
                        return filePath;
                    }

                }
            }
        }
        return null;
    }

    /**
     * 判断用户是否关注Tokenswap_DEX推特账号
     *
     * @param chatId             聊天唯一标识
     * @param twitterAccountName 推特账号名称
     * @return 是否关注Tokenswap_DEX推特账号
     */
    public Boolean whetherAttentionTokenSwapDex(String chatId, String twitterAccountName) {
        String uri = TWITTER_URL + "/friends/list.json?cursor=-1&screen_name=" + twitterAccountName + "&skip_status=true&include_user_entities=false";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.add("Authorization", bearerToken);
        HttpEntity<String> entity = new HttpEntity<>(headers);
        try {
            String strBody = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class).getBody();
            log.info("判断用户是否关注某个推特账号的结果：{}", strBody);
            JSONObject twitterFriendResponse = JSON.parseObject(strBody);
            if (null != twitterFriendResponse && twitterFriendResponse.containsKey("users")) {
                JSONArray userJsonArray = twitterFriendResponse.getJSONArray("users");
                if (!CollectionUtils.isEmpty(userJsonArray)) {
                    JSONObject userJson;
                    for (Object userObject : userJsonArray) {
                        userJson = JSON.parseObject(JSON.toJSONString(userObject));
                        if (null != userJson && userJson.containsKey("screen_name")) {
                            if (twitterAccount.equalsIgnoreCase(userJson.getString("screen_name"))) {
                                return true;
                            }
                        }

                    }
                }
            }
        } catch (RestClientException e) {
            log.error("判断用户是否关注Tokenswap_DEX推特账号发生异常：", e);
            FocusOnTwitterFailure focusOnTwitterFailure = new FocusOnTwitterFailure();
            focusOnTwitterFailure.setTwitterAccountName(twitterAccountName);
            focusOnTwitterFailure.setChatId(chatId);
            chatTwitterService.insertFocusOnTwitterFailure(focusOnTwitterFailure);
            return false;
        }
        return false;
    }

    /**
     * 发送POST请求任务
     *
     * @param reqMethod 请求方法
     * @param params    请求参数
     * @return 结果
     */
    public String sendRpcReq(String reqMethod, List<Object> params) {
        //设置请求参数
        Map<String, Object> requestJson = Maps.newHashMapWithExpectedSize(1 << 4);
        requestJson.put("jsonrpc", "2.0");
        requestJson.put("id", 1);
        requestJson.put("method", reqMethod);
        requestJson.put("params", params);
        String requestBody = JSON.toJSONString(requestJson);
        log.info("请求体数据：【{}】", requestBody);
        HttpEntity<String> formEntity = new HttpEntity<>(requestBody, getJsonHeader());
        HttpMethod method = HttpMethod.POST;
        ResponseEntity<String> response = restTemplate.exchange(walletUrl, method, formEntity, String.class);
        String body = response.getBody();
        log.info("返回的响应数据：{}", body);
        return body;
    }

    /**
     * 发送消息
     *
     * @param chatId 群组唯一标识
     * @param text   发送的内容
     */
    @Async
    public void sendMessage(Long chatId, String text) {
        log.info("发送的内容：{}", text);
        String uri = telegramUrl + "/bot" + taskToken + "/sendMessage?chat_id=" + chatId + "&text=" + text + "&parse_mode=HTML";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> entity = new HttpEntity<>(headers);
        String strBody = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class).getBody();
        log.info("发送的消息的响应:{}", strBody);
    }

    /**
     * 发送重新发送截图的消息
     *
     * @param chatId      群组唯一标识
     * @param messageText 发送的内容
     */
    @Async
    public void sendReSendPhoto(Long chatId, Message messageText) throws InterruptedException {
        // 睡个10秒，避免刷屏
        TimeUnit.SECONDS.sleep(10);
        StringBuilder sb = new StringBuilder(1 << 4);
        sb.append("@");
        User fromUser = messageText.getFrom();
        if (null != fromUser) {
            String userName = fromUser.getUserName();
            if (StringUtils.isBlank(userName)) {
                userName = fromUser.getFirstName() + fromUser.getLastName();
            }
            sb.append(userName);
        }
        sb.append(" Please do not send compressed images,");
        sb.append("Refer to the following methods to send the task screenshot, otherwise it will be invalid.");
        String imageUrl = "<a href=" + "\"" + checkImageUrl + "\"" + ">.</a>";
        String text = imageUrl + "\r\n" + sb.toString();
        log.info("发送的内容：{}", text);
        String uri = telegramUrl + "/bot" + collectToken + "/sendMessage?chat_id=" + chatId + "&text=" + text + "&parse_mode=HTML";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> entity = new HttpEntity<>(headers);
        String strBody = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class).getBody();
        log.info("发送重新发送截图的消息的响应:{}", strBody);
    }

    /**
     * 构造http请求的头部信息
     *
     * @return http头部信息
     */
    private HttpHeaders getJsonHeader() {
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add(ACCEPT, MediaType.APPLICATION_JSON.toString());
        return headers;
    }

//    public static void main(String[] args) throws IOException {
//        System.out.println(URLEncoder.encode("-1", "UTF-8"));
//        System.out.println(URLEncoder.encode("yifeitang9", "UTF-8"));
//        sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
//        String source = "vXsZC0uS6mdvIWPuBYpmj3Hmp:OfwpFw185qyddZGrXelN9b1VCsInKpYDeHVm8J8cmIXCvJV96n";
//        System.out.println(new sun.misc.BASE64Encoder().encode(decoder.decodeBuffer(source)));
//        System.out.println("++++++++++++++++++++++++++");
//        byte[] encodeBase64 = Base64.encodeBase64(source.getBytes("UTF-8"));
//        System.out.println("RESULT: " + new String(encodeBase64));
//    }

}
